package com.xin.ruanjian.omsystem.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.xin.ruanjian.omsystem.R;

/**
 * Created by local123 on 2018/2/3.
 */

public class GlideUtils {

    /**
     * load normal  for img
     *
     * @param url
     * @param erroImg
     * @param emptyImg
     * @param iv
     */
    public static void glideLoader(Context context, String url, int erroImg, int emptyImg, ImageView iv) {
        //原生 API
        Glide.with(context).load(url).diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(emptyImg).error(erroImg).into(iv);
    }
    /**
     * load normal  for  circle or round img
     *
     * @param url
     * @param iv
     * @param tag
     */
    public static void glideLoader(final Context context, String url, final ImageView iv, Shape tag) {
        if (Shape.SQUARE == tag) {
            Glide.with(context)
                    .load(url)
                    .placeholder(R.mipmap.ic_launcher_round).error(R.mipmap.ic_launcher_round)
                    .transform(new FitCenter(context), new GlideCircleTransform(context))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .crossFade()
                    .into(iv);
        } else if (Shape.ROUND == tag) {
            Glide.with(context)
                    .load(url)
                    .placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher)
                    .transform(new FitCenter(context), new GlideRoundTransform(context))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .crossFade()
                    .into(iv);
        }else if (Shape.CIRCLE == tag){
            Glide.with(context)
                    .load(url)
                    .asBitmap()  //这句不能少，否则下面的方法会报错
                    .centerCrop()
                    .error(R.mipmap.ic_launcher_round)
                    .into(new BitmapImageViewTarget(iv) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                            circularBitmapDrawable.setCircular(true);
                            iv.setImageDrawable(circularBitmapDrawable);
                        }
                    });
        }
    }

    public enum Shape {
        SQUARE, CIRCLE, ROUND, NOMAL
    }
}
